import { useEffect, useState } from "react";
import { Modal, Form, Input, Row, Col, Select, Tooltip, message, Button, Checkbox } from "antd"
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { cloneDeep } from 'lodash'
import { TextWidget, getMessage } from '@inbiz/react';
import PageLoading from "@inbiz/basic/PageLoading";
import { InbizIcon, uuid } from "@inbiz/utils";
import MemberSelect from "@inbiz/basic/MemberSelect";
import { conditionData, enumGroupType, enumPerm, enumRoleType, groupTypeData, logicData, roleTypeData, userTypeData } from "./const";
import { getModelFieldList, getModelList, getModelQuery, getPermMemberDetail, getQueryFieldList, getRuleDetail, postDataPermRule, putDataPermRule } from "../service";
import { IDataPermGroup, IdefaultObj } from "./data";
import SelectUser from "./SelectUser";

const { Option, OptGroup } = Select;

// 创建人初始数据（固定）
const creatorsInfo = {
  MemberId: '516fb90d601a4f2a8eb9c43e4ff2bfb3',
  MemberType: 6,
  MemberName: 'Everyone',
  PermValue: 7,
};

// 默认组数据
const defaultGroup: IDataPermGroup = {
  Id: uuid(10),
  Conditions: [
    {
      Id: uuid(10),
      Field: 'creatorid',
      Operator: 'eq',
      Type: enumGroupType.Variable,
      Variable: { Key: 'currentUser' },
      Value: '',
      Name: '',
      Connector: 'And',
    },
  ],
  MemberPermList: [creatorsInfo],
};

// 默认弹窗大对象
const defaultObj: IdefaultObj = {
  Name: '',
  Type: enumRoleType.Model,
  TypeKey: undefined,
  ModelName: '',
  Remark: '',
  DataPermGroup: [defaultGroup],
};

// 数值转换成数组：7 => [1,2,4]
const valueAsArrayFormat = (val?: any) => {
  const arr = Object.values(enumPerm);

  for (let i = arr.length - 1; i >= 0; i--) {
    if ((val & arr[i]) !== arr[i]) {
      arr.splice(i, 1);
    }
  }
  return arr;
};

const RoleConfig = (props: any) => {
  const {
    visible,
    onSuccess,
    onCancel,
    isEdit,
    appId,
    currentItem,
    currentModule,
  } = props;
  // 当前表单数据
  const [currentObj, $currentObj] = useState<any>(null)
  // 模型数据
  const [modelData, $modelData] = useState<any[]>([])
  // 查询器数据
  const [queryData, $queryData] = useState<any[]>([])
  // 字段数据
  const [FieldData, $FieldData] = useState<any[]>([])
  // 当前选中的模型/查询器数据
  const [currentModel, $currentModel] = useState<any>(null)
  // 是否全屏
  const [isfullModal, $isfullModal] = useState<boolean>(false)
  // 是否显示成员选择弹窗
  const [memberSelectVisible, $memberSelectVisible] = useState(false);
  // 当前分组
  const [currentGroup, $currentGroup] = useState<any>(null)
  // 当前条件
  const [currentCondition, $currentCondition] = useState<any>(null)
  // condition列表当前选中成员数据
  const [currentMemberSelected, $currentMemberSelected] = useState([])
  // 保存loading
  const [confirmLoading, $confirmLoading] = useState<boolean>(false)
  // 区分权限对象和条件单选成员选择 (condition | user)
  const [memberType, $memberType] = useState('')
  const [form] = Form.useForm()

  // 初始化请求模型和查询器数据
  useEffect(() => {
    getModelData();
    getModelQueryData();
  }, []);

  // 编辑，需请求、重组数据
  useEffect(() => {
    if (isEdit) {
      getRuleDetailInfo();
    } else {
      $currentObj(defaultObj);
    }
  }, [isEdit, currentItem]);

  // 获取模型列表
  const getModelData = () => {
    getModelList({
      appId
    }).then(res => {
      if (!res) return;
      $modelData(res);
    });
  };

  // 获取查询器列表
  const getModelQueryData = () => {
    getModelQuery().then(res => {
      if (!res) return;
      $queryData(res);
    });
  };

  // 根据模型/查询器key获取字段列表
  const getFieldList = (key: any, type?: boolean, fn?: Function, modelName?: string) => {
    if (type) {
      // 查询器
      getQueryFieldList({
        appId,
        key,
      }).then((res: any) => {
        if (!Array.isArray(res)) return;
        $FieldData(trsansModelData(res));
        fn?.()
      });
    } else {
      // 模型
      getModelFieldList({
        appId,
        ignoreSystem: false,
        modelKey: key,
      }).then((res: any) => {
        if (Array.isArray(res?.ModelAttr)) {
          let act: any[] = res.ModelAttr.map((i: any) => ({ ...i, ModelName: modelName }))
          if (Array.isArray(res.RelationAttr) && res.RelationAttr.length) {
            res.RelationAttr.forEach((item: any) => {
              if (!act.find((i: any) => i.Name === item.Name)) {
                act.push(item)
              }
            })
          }
          $FieldData(act);
          return
        }
        $FieldData([])
      });
    }
  };

  // 4. 编辑>获取规则详情
  const getRuleDetailInfo = () => {
    getRuleDetail({
      id: currentItem?.Id,
    }).then(res => {
      if (!res) return;
      // 1.获取并组装数据
      // Conditions[]Item,添加自增Id等数据转换
      res.forEach((item: any) => {
        item.Conditions.forEach((cond: any) => {
          cond.Id = uuid(10);
          if (currentItem?.Type == 1) {
            cond.Field = `${cond.ModelName}$${cond.Field}`
          }
          cond.MemberSelected = cond.MemberSelected ? JSON.parse(cond.MemberSelected) : [];
          cond.Connector = cond.Connector == 1 ? 'Or' : 'And';
        });
        item.Connector = item.Connector == 1 ? 'Or' : 'And';
      });

      let data = {
        ...currentItem,
        DataPermGroup: res,
      };
      const arr: any[] = [];
      res.forEach((item: any) => {
        arr.push(getPermMemberDetail({ id: item.Id }));
      });
      Promise.all(arr).then(ress => {
        ress.forEach((item, index) => {
          data.DataPermGroup[index].MemberPermList = item.MemberPermList;
        });
        $currentObj(data);
        // 2. 做数据初始化(请求对应模型/查询器获取字段)
        let obj: any = {
          children: currentItem.TypeName,
          id: currentItem.TypeKey
        }
        if (currentItem.Type == 1) {
          obj['data-v'] = { ModelName: currentItem.ModelName }
        }
        $currentModel(obj);
        getFieldList(currentItem.TypeKey, currentItem?.Type == 1);
      });
    });
  };

  // 查询器关联模型数据转换处理
  const trsansModelData = (list: any[]) => {
    let data: any[] = []
    list.forEach((i: any) => {
      let idx = data.findIndex((v: any) => v.Key === i.ModelKey)
      if (idx >= 0) {
        // 已有此模型数据-添加字段
        data[idx].Children.push({
          Key: i.FieldName,
          Name: i.FieldName.substr(i.FieldName.indexOf('$') + 1)
        })
      } else {
        // 没有此模型数据-添加模型和字段
        data.push({
          Key: i.ModelKey,
          Name: i.ModelName,
          Children: [{
            Key: i.FieldName,
            Name: i.FieldName.substr(i.FieldName.indexOf('$') + 1)
          }]
        })
      }
    })
    return data
  }

  // 类型切换（切换前提示）
  const onTypeChange = (val: any) => {
    const obj = cloneDeep(currentObj);
    obj.Type = val;
    obj.TypeKey = undefined;

    obj.DataPermGroup = [
      {
        ...cloneDeep(defaultGroup),
        Id: uuid(10),
      },
    ];
    $currentObj(obj);
    $FieldData([])
    form.setFieldsValue({
      TypeKey: undefined,
    });
  };

  // 模型or查询器change
  const onModelChange = (val: any, symbol: any) => {
    $currentModel(symbol.props);
    const fn = () => {
      const obj = cloneDeep(currentObj);
      obj.DataPermGroup = [
        {
          ...cloneDeep(defaultGroup),
          Id: uuid(10),
        },
      ];
      // 查询器添加默认模型字段
      if (symbol.props?.['data-v']) {
        let key = `${symbol.props?.['data-v'].ModelName}$creatorid`
        obj.DataPermGroup[0].Conditions[0].Field = key
      }
      $currentObj(obj);
    }
    if (symbol.props?.['data-v']) {
      getFieldList(val, currentObj?.Type == '1', fn);
    } else {
      fn()
      getFieldList(val, currentObj?.Type == '1', undefined, symbol.props?.children);
    }
  };

  // 添加组
  const onAddGroup = (index: number) => {
    const obj = cloneDeep(currentObj);
    let opt = {
      ...cloneDeep(defaultGroup),
      Id: uuid(10),
    };
    opt.Conditions[0].Field = ''
    obj.DataPermGroup.splice(index + 1, 0, opt);
    $currentObj(obj);
  };

  // 删除组
  const onDeleteGroup = (group?: any) => {
    Modal.confirm({
      title: <TextWidget>Permission.warning</TextWidget>, // 警告
      content: <TextWidget>Permission.del_perm_group_warn</TextWidget>, // 删除后不可恢复，确认删除此权限组吗？
      okText: <TextWidget>global.sure</TextWidget>, // 确定
      cancelText: <TextWidget>global.cancel</TextWidget>, // 取消
      onOk() {
        const obj = cloneDeep(currentObj);
        const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
        obj.DataPermGroup.splice(index, 1);
        $currentObj(obj);
      }
    })
  };

  // 添加配置条件
  const onAddCondition = (group: any, itemIndex: number) => {
    const obj = cloneDeep(currentObj);
    let opt = {
      ...cloneDeep(defaultGroup.Conditions[0]),
      Field: '',
      Id: uuid(10),
    };

    obj.DataPermGroup.forEach((item: any) => {
      if (item.Id == group.Id) {
        item.Conditions.splice(itemIndex + 1, 0, opt);
      }
    });
    $currentObj(obj);
  };

  // 删除配置条件
  const onDeleteCondition = (group: any, item: any) => {
    const obj = cloneDeep(currentObj);
    obj.DataPermGroup.forEach((entry: any) => {
      if (entry.Id == group.Id) {
        const index = entry.Conditions.findIndex((cond: any) => cond.Id == item.Id);
        entry.Conditions.splice(index, 1);
      }
    });
    $currentObj(obj);
  };

  // 条件>条件符号change
  const onConditionSymbolChange = (val: any, group: any, item: any) => {
    const obj = cloneDeep(currentObj);
    const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
    const indexConditions = obj.DataPermGroup[index].Conditions.findIndex((cond: any) => cond.Id == item.Id);
    obj.DataPermGroup[index].Conditions[indexConditions].Operator = val;
    $currentObj(obj);
  };

  // 条件>类型change
  const onConditionTypeChange = (val: any, group: any, item: any) => {
    const obj = cloneDeep(currentObj);
    const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
    const indexConditions = obj.DataPermGroup[index].Conditions.findIndex((cond: any) => cond.Id == item.Id);
    obj.DataPermGroup[index].Conditions[indexConditions].Type = val;
    // 变量>赋初始值
    if (val.toString() == enumGroupType.Variable) {
      obj.DataPermGroup[index].Conditions[indexConditions].Variable = {
        Key: 'currentUser',
      };
      form.setFieldsValue({
        DataPermGroup: {
          [group.Id]: {
            Conditions: {
              [item.Id]: {
                Variable: {
                  Key: 'currentUser'
                }
              }
            }
          }
        }
      })
    } else {
      obj.DataPermGroup[index].Conditions[indexConditions].Name = '';
      obj.DataPermGroup[index].Conditions[indexConditions].Value = '';
      obj.DataPermGroup[index].Conditions[indexConditions].MemberSelected = [];
      $currentMemberSelected([])
      form.setFieldsValue({
        DataPermGroup: {
          [group.Id]: {
            Conditions: {
              [item.Id]: {
                Name: '',
                Value: ''
              }
            }
          }
        }
      })
    }
    $currentObj(obj);
  };

  // 条件>用户类型change
  const onUserTypeChange = (val: any, group: any, item: any) => {
    const obj = cloneDeep(currentObj);
    const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
    const indexConditions = obj.DataPermGroup[index].Conditions.findIndex((cond: any) => cond.Id == item.Id);
    obj.DataPermGroup[index].Conditions[indexConditions].Variable.Key = val;
    obj.DataPermGroup[index].Conditions[indexConditions].Value = '';
    obj.DataPermGroup[index].Conditions[indexConditions].Name = '';
    obj.DataPermGroup[index].Conditions[indexConditions].MemberSelected = [];
    $currentMemberSelected([])
    form.setFieldsValue({
      DataPermGroup: {
        [group.Id]: {
          Conditions: {
            [item.Id]: {
              Name: '',
              Value: ''
            }
          }
        }
      }
    })
    $currentObj(obj);
  };

  // 删除用户选择Tag
  const onDeleteTag = (group: any, item: any, tagIndex: number) => {
    const obj = cloneDeep(currentObj);
    const groupIndex = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
    const conditionsIndex = obj.DataPermGroup[groupIndex].Conditions.findIndex((cond: any) => cond.Id == item.Id);

    let names = obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Name.split(',');
    let values = obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Value.split(',');

    if (names.length > 1) {
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Name = names
        .filter((_: any, index: number) => index != tagIndex)
        .join(',');
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Value = values
        .filter((_: any, index: number) => index != tagIndex)
        .join(',');
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].MemberSelected?.splice(tagIndex, 1);
    } else {
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Name = '';
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].Value = '';
      obj.DataPermGroup[groupIndex].Conditions[conditionsIndex].MemberSelected = [];
    }
    // @@ 这是antd V4的写法
    form.setFieldsValue({
      DataPermGroup: {
        [group.Id]: {
          Conditions: {
            [item.Id]: {
              Name: names.filter((_: any, index: number) => index != tagIndex).join(','),
              Value: values.filter((_: any, index: number) => index != tagIndex).join(',')
            }
          }
        }
      }
    })
    // @@ 下面的是antd V3的写法
    // const fileName = `DataPermGroup[${group.Id}].Conditions[${item.Id}].Name`;
    // const fileValue = `DataPermGroup[${group.Id}].Conditions[${item.Id}].Value`;
    // form.setFieldsValue({
    //   [fileName]: names.filter((_: any, index: number) => index != tagIndex).join(','),
    //   [fileValue]: values.filter((_: any, index: number) => index != tagIndex).join(',')
    // })
    $currentObj(obj);
  };

  // 添加用户权限(弹窗)
  const openMemberSelect = (group: any, name: any, item?: any) => {
    if (item?.Variable?.Key === 'currentUser' || item?.Variable?.Key === 'currentDepartment') {
      return;
    }
    $currentGroup(group);
    $memberSelectVisible(true);
    $memberType(name);
    $currentCondition(item ?? null);
    if (item?.MemberSelected?.length) {
      let arr = item.MemberSelected.map((item: any) => ({
        id: item.Id,
        name: item.Name,
        key: item.key
      }))
      $currentMemberSelected(arr);
    } else {
      $currentMemberSelected([]);
    }
  };

  // 添加用户权限
  const onAddUser = (rows: any) => {
    // if (rows?.length == 0) return;
    const obj = cloneDeep(currentObj);
    const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == currentGroup.Id);
    if (memberType == 'condition') {
      obj.DataPermGroup[index].Conditions.forEach((entry: any) => {
        if (entry.Id == currentCondition.Id) {
          let tmpValue: any[] = [];
          let tmpName: any = [];
          // 成员选中item用作反选
          let tmpMemberSelected: any[] = [];
          rows.forEach((row: any) => {
            tmpValue.push(row.id);
            tmpName.push(row.name);
            tmpMemberSelected.push({ key: row.key, Id: row.id, Name: row.name });
          });
          entry.MemberSelected = tmpMemberSelected;
          entry.Value = tmpValue.join(',');
          entry.Name = tmpName.join(',');
          // @@ 这是antd V4的写法
          form.setFieldsValue({
            DataPermGroup: {
              [currentGroup.Id]: {
                Conditions: {
                  [entry.Id]: {
                    Name: tmpName.join(','),
                    Value: tmpValue.join(',')
                  }
                }
              }
            }
          })
          // @@ 下面的是antd V3的写法
          // const fileName = `DataPermGroup[${currentGroup.Id}].Conditions[${entry.Id}].Name`;
          // const fileValue = `DataPermGroup[${currentGroup.Id}].Conditions[${entry.Id}].Value`;
          // form.setFieldsValue({
          //   [fileName]: tmpName.join(','),
          //   [fileValue]: tmpValue.join(',')
          // })
        }
      });
    } else {
      rows.forEach((item: any) => {
        let flag = false;
        // 去重
        obj.DataPermGroup[index].MemberPermList.forEach((entry: any) => {
          if (entry.MemberId == item.id) {
            flag = true;
          }
        });
        if (!flag) {
          obj.DataPermGroup[index].MemberPermList.push({
            MemberId: item.id,
            MemberType: (item.memberarea == 3 && item.name == 'Everyone') ? 6 : item.memberarea,
            MemberName: item.name,
            PermValue: (item.memberarea == 3 && item.name == 'Everyone') ? 7 : 1,
          });
        }
      });
    }
    $currentObj(obj);
  };

  // 删除用户权限
  const onDeleteUser = (group: any, item: any) => {
    const obj = cloneDeep(currentObj);
    obj.DataPermGroup.forEach((entry: any) => {
      if (entry.Id == group.Id) {
        const index = entry.MemberPermList.findIndex((member: any) => member.MemberId == item.MemberId);
        entry.MemberPermList.splice(index, 1);
      }
    });
    $currentObj(obj);
  };

  // 用户权限变更(查看、编辑、删除)
  const onChangeUserPerm = (values: any, item: any, group: any) => {
    const obj = cloneDeep(currentObj);
    const index = obj.DataPermGroup.findIndex((entry: any) => entry.Id == group.Id);
    const indexUser = obj.DataPermGroup[index].MemberPermList.findIndex((member: any) => member.MemberId == item.MemberId);

    let newValues: any[] = [];
    if (values.includes(enumPerm.delete) && values.includes(enumPerm.edit)) {
      // 编辑+删除
      obj.DataPermGroup[index].MemberPermList[indexUser].PermValue = 7;
      newValues = [1, 2, 4];
    } else if (values.includes(enumPerm.delete)) {
      // 删除
      obj.DataPermGroup[index].MemberPermList[indexUser].PermValue = 5;
      newValues = [1, 4];
    } else if (values.includes(enumPerm.edit)) {
      // 编辑
      obj.DataPermGroup[index].MemberPermList[indexUser].PermValue = 3;
      newValues = [1, 2];
    } else if (values.includes(enumPerm.view)) {
      // 查看
      obj.DataPermGroup[index].MemberPermList[indexUser].PermValue = 1;
      newValues = [1];
    } else {
      obj.DataPermGroup[index].MemberPermList[indexUser].PermValue = 0;
    }
    // 存储数据
    $currentObj(obj);
    if (newValues.length) {
      const groutId = obj.DataPermGroup[index].Id;
      const memberId = obj.DataPermGroup[index].MemberPermList[indexUser].MemberId;
      // @@ 这是antd V4的写法
      form.setFieldsValue({
        DataPermGroup: {
          [groutId]: {
            MemberPermList: {
              [memberId]: {
                PermValue: newValues
              }
            }
          }
        }
      });
      // @@ 下面的是antd V3的写法
      // const fileName = `DataPermGroup[${groutId}].MemberPermList[${memberId}].PermValue`;
      // form.setFieldsValue({
      //   [fileName]: newValues,
      // });
    }
  };

  const Tips = ({ text }: { text: any }) => {
    return (
      <Tooltip placement="top" title={text}>
        <ExclamationCircleOutlined />：
      </Tooltip>
    );
  };

  const modalProps = {
    visible,
    width: 1002,
    wrapClassName: isfullModal ? 'inbiz-comp-permission-data-role-config inbiz-comp-permission-data-role-config-full' : 'inbiz-comp-permission-data-role-config',
    confirmLoading: confirmLoading,
    onCancel: () => {
      onCancel?.()
      $isfullModal(false)
      $confirmLoading(false)
    },
    onOk: () => {
      $confirmLoading(true)
      form.validateFields().then((values: any) => {
        // 数据处理
        const dataFormat = (data: any, type?: any) => {
          let result = [];
          for (let i in data) {
            if (type == 'permObject') {
              data[i].PermValue = eval(data[i].PermValue.join('+'));
            } else if (type == 'permCondition') {
              if (data[i].Field.indexOf('$') >= 0) {
                data[i].ModelName = data[i].Field.substr(0, data[i].Field.indexOf('$'))
                data[i].Field = data[i].Field.substr(data[i].Field.indexOf('$') + 1)
              } else {
                data[i].ModelName = currentModel?.children;
              }
              data[i].MemberSelected = JSON.stringify(dataFormat(data[i].MemberSelected || {}));
            }
            result.push(data[i]);
          }
          return result;
        }
        const { Id, Name, Type, TypeKey, Remark } = values;
        let DataPermGroup = dataFormat(values.DataPermGroup);
        DataPermGroup.forEach(group => {
          group.Conditions = dataFormat(group.Conditions, 'permCondition');
          group.MemberPermList = dataFormat(group.MemberPermList, 'permObject');
        });
        let params = {
          Id,
          Name,
          Type,
          TypeName: currentModel?.children, // 模型名称 | 查询器名称
          TypeKey,
          Remark,
          ModelName: Type == 1 ? currentModel?.['data-v']?.ModelName : currentModel?.children, // 查询器主模型 | 模型名称
          ModuleId: currentModule, // 左侧模块Id
          DataPermGroup,
        };
        const fn = isEdit ? putDataPermRule : postDataPermRule
        fn(params).then((res: any) => {
          if (!res) return;
          message.success(isEdit ? <TextWidget>Permission.perm_edit_succ</TextWidget> : <TextWidget>Permission.perm_add_succ</TextWidget>); // 编辑:新建 数据权限成功
          onSuccess();
          $isfullModal(false)
          $confirmLoading(false)
        }).catch(() => {
          $confirmLoading(false)
        });
      }).catch(() => {
        $confirmLoading(false)
      })
    },
    closable: false,
    title:
      <div className='role-config-modal-title'>
        <span><TextWidget>Permission.perm_role_title</TextWidget></span>
        <div>
          <InbizIcon
            type={isfullModal ? "icon-huanyuan" : "icon-ic-zuidahua"}
            onClick={() => $isfullModal(!isfullModal)}
            style={{ marginRight: 10 }}
          />
          <InbizIcon
            type="icon-ic-close-bold"
            onClick={() => {
              onCancel?.()
              $isfullModal(false)
            }}
          />
        </div>
      </div>
  };

  const memberSelectProps = {
    visible: memberSelectVisible,
    config: {
      multiple: true,
      selected: currentCondition?.Variable?.Key ? currentMemberSelected : [],
      tabs: currentCondition?.Variable?.Key
        ? [currentCondition?.Variable?.Key]
        : ['department', 'group', 'user'],
      onCancel: () => $memberSelectVisible(false),
      onOk: (keys: any, rows: any) => {
        onAddUser(rows);
        $memberSelectVisible(false);
      },
    },
  };

  return (
    <>
      <Modal {...modalProps}>
        {currentObj ? (
          <Form form={form} labelCol={{ span: 24 }} wrapperCol={{ span: 24 }}>
            {/* 记录id */}
            <Form.Item
              name='Id'
              style={{ display: 'none' }}
              initialValue={currentObj?.Id || ''}
            >
              <Input />
            </Form.Item>
            {/* 头部表单 */}
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  name="Name"
                  label={<span><TextWidget>Permission.perm_names</TextWidget>：</span>} // 权限名称
                  initialValue={currentObj?.Name || ''}
                  rules={[
                    { required: true, message: getMessage('Permission.perm_name_null') },
                    { max: 30, message: getMessage('Permission.perm_name_max') },
                  ]}
                >
                  <Input placeholder={getMessage('Permission.perm_modu_name_plac')} />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name='Type'
                  label={
                    <span>
                      <TextWidget>Permission.type</TextWidget> <Tips text={getMessage('Permission.perm_type_warn')} />
                    </span>
                  }
                  initialValue={currentObj?.Type?.toString() || enumRoleType.Model}
                >
                  <Select onChange={onTypeChange} placeholder={getMessage('Permission.perm_please_sele')}>
                    {roleTypeData?.map(item => (
                      <Option key={item.value} value={item.value}>
                        <TextWidget>{item.label}</TextWidget>
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                {currentObj?.Type == enumRoleType.Model ? (
                  <Form.Item
                    name='TypeKey'
                    label={
                      <span>
                        <TextWidget>Permission.perm_sele_model</TextWidget> <Tips text={getMessage('Permission.perm_model_warn')} />
                      </span>
                    }
                    initialValue={currentObj?.TypeKey || undefined}
                    rules={[{ required: true, message: getMessage('Permission.perm_model_null') }]}
                  >
                    <Select
                      onChange={onModelChange}
                      placeholder={getMessage('Permission.perm_please_sele')}
                      virtual={false}
                      showSearch
                      optionFilterProp="label"
                      filterOption={(input, option) => {
                        if (typeof option?.props?.children == 'string') {
                          return (option?.props?.children ?? '')?.toLowerCase().includes(input.toLowerCase())
                        } else {
                          return false
                        }
                      }}
                    >
                      {modelData.length &&
                        modelData?.map((item: any) => (
                          <Option key={item.ModelKey} value={item.ModelKey} title={item.ModelName}>
                            {item.ModelName}
                          </Option>
                        ))}
                    </Select>
                  </Form.Item>
                ) : (
                  <Form.Item
                    name='TypeKey'
                    label={
                      <span>
                        <TextWidget>Permission.perm_sele_query</TextWidget> <Tips text={getMessage('Permission.perm_query_warn')} />
                      </span>
                    }
                    initialValue={currentObj?.TypeKey || undefined}
                    rules={[{ required: true, message: getMessage('Permission.perm_query_null') }]}
                  >
                    <Select
                      onChange={onModelChange}
                      placeholder={getMessage('Permission.perm_please_sele')}
                      virtual={false}
                      showSearch
                      optionFilterProp="label"
                      filterOption={(input, option) => {
                        if (typeof option?.props?.children == 'string') {
                          return (option?.props?.children ?? '')?.toLowerCase().includes(input.toLowerCase())
                        } else {
                          return false
                        }
                      }}
                    >
                      {queryData?.map((item: any) => (
                        <Option key={item.Key} value={item.Key} data-v={item} title={item.Name}>
                          {item.Name}
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                )}
              </Col>
              <Col span={24}>
                <Form.Item
                  name='Remark'
                  label={<span><TextWidget>Permission.perm_mark</TextWidget>：</span>}
                  initialValue={currentObj?.Remark || ''}
                  rules={[{ max: 200, message: getMessage('Permission.perm_mark_max') }]}
                  style={{ marginTop: -6 }}
                >
                  <Input.TextArea rows={2} placeholder={getMessage('Permission.perm_mark_placeholder')} />
                </Form.Item>
              </Col>
            </Row>

            <Row>
              <Col span={12} className='role-config-condition-title'>
                {/* 配置业务条件 */}
                <TextWidget>Permission.perm_setting</TextWidget>：
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                <Button onClick={() => onAddGroup(0)} type="primary">
                  {/* 添加组 */}
                  <TextWidget>Permission.perm_add_group</TextWidget>
                </Button>
                {currentObj?.DataPermGroup?.length > 1 && (
                  <Button
                    onClick={() => onDeleteGroup(currentObj?.DataPermGroup[0])}
                    type='primary'
                    danger
                    ghost
                    style={{ marginLeft: 20 }}
                  >
                    {/* 删除组 */}
                    <TextWidget>Permission.perm_del_group</TextWidget>
                  </Button>
                )}
              </Col>
            </Row>

            {currentObj?.DataPermGroup?.map((group: any, groupIndex: number) => (
              <>
                {/* // 添加组 删除组 */}
                {groupIndex > 0 && (
                  <div className='role-config-btns'>
                    <div className='role-config-btns-left'>
                      <Form.Item
                        // name={`DataPermGroup[${group.Id}].Connector`}
                        name={['DataPermGroup', group.Id, 'Connector']}
                        initialValue={group.Connector || 'And'}
                      >
                        <Select style={{ width: 80 }} placeholder={getMessage('Permission.perm_please_sele')}>
                          {logicData?.map((opt: any) => (
                            <Option key={opt.value} value={opt.value}>
                              <TextWidget>{opt.label}</TextWidget>
                            </Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </div>
                    <div className='role-config-btns-right'>
                      <Button onClick={() => onAddGroup(groupIndex)} type="primary">
                        {/* 添加组 */}
                        <TextWidget>Permission.perm_add_group</TextWidget>
                      </Button>
                      <Button
                        onClick={() => onDeleteGroup(group)}
                        danger
                        ghost
                        style={{ marginLeft: 20 }}
                      >
                        {/* 删除组 */}
                        <TextWidget>Permission.perm_del_group</TextWidget>
                      </Button>
                    </div>
                  </div>
                )}

                {/* // 组内数据 */}
                <div key={group.Id} className='role-config-group'>
                  <Form.Item
                    // name={`DataPermGroup[${group.Id}].Id`}
                    name={['DataPermGroup', group.Id, 'Id']}
                    style={{ display: 'none' }}
                    initialValue={group.Id || ''}
                  >
                    <Input />
                  </Form.Item>
                  <div>
                    {group.Conditions?.map((item: any, itemIndex: number) => (
                      <Row gutter={16} key={item.Id} style={{ padding: '0 10px' }}>
                        <Col span={2}>
                          <Form.Item
                            // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Connector`}
                            name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Connector']}
                            initialValue={item.Connector}
                            rules={group.Conditions?.length == 1 || group.Conditions?.length == itemIndex + 1
                              ? []
                              : [{ required: true, message: getMessage('Permission.not_null') }]}
                          >
                            <Select placeholder={getMessage('Permission.perm_please_sele')} disabled={itemIndex === 0}>
                              {logicData?.map(opt => (
                                <Option key={opt.value} value={opt.value} title={getMessage(opt.label)}>
                                  <TextWidget>{opt.label}</TextWidget>
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>
                        </Col>
                        {/* 字段 */}
                        <Col span={4}>
                          <Form.Item
                            // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Field`}
                            name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Field']}
                            initialValue={item.Field || undefined}
                            rules={[{ required: true, message: getMessage('Permission.filed_null') }]}
                          >
                            <Select
                              placeholder={getMessage('Permission.perm_please_sele')}
                              showSearch
                              virtual={false}
                              optionFilterProp="label"
                              filterOption={(input, option) => {
                                if (typeof option?.props?.children == 'string') {
                                  return (option?.props?.children ?? '')?.toLowerCase().includes(input.toLowerCase())
                                } else {
                                  return false
                                }
                              }}
                            >
                              {FieldData?.map(opt => {
                                if (opt.Children) {
                                  return (
                                    <OptGroup key={opt.Key} label={opt.Name}>
                                      {
                                        opt.Children?.map((v: any) => (
                                          <Option key={v.Key} value={v.Key} title={v.Name}>
                                            {v.Name}
                                          </Option>
                                        ))
                                      }
                                    </OptGroup>
                                  )
                                } else {
                                  return (
                                    <Option key={opt.Key} value={opt.Name} title={opt.Name}>
                                      {opt.Name}
                                    </Option>
                                  )
                                }
                              })}
                            </Select>
                          </Form.Item>
                        </Col>
                        {/* 条件符号 */}
                        <Col span={3}>
                          <Form.Item
                            // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Operator`}
                            name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Operator']}
                            initialValue={item.Operator || undefined}
                            rules={[{ required: true, message: getMessage('Permission.operator_null') }]}
                          >
                            <Select
                              placeholder={getMessage('Permission.perm_please_sele')}
                              onChange={val => onConditionSymbolChange(val, group, item)}
                              virtual={false}
                            >
                              {conditionData?.map(opt => (
                                <Option key={opt.value} value={opt.value} title={getMessage(opt.label)}>
                                  <TextWidget>{opt.label}</TextWidget>
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>
                        </Col>
                        {/* 类型-输入/变量 */}
                        <Col span={3}>
                          <Form.Item
                            // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Type`}
                            name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Type']}
                            initialValue={item.Type?.toString() || enumGroupType.Variable}
                            rules={[{ required: true, message: getMessage('Permission.not_null') }]}
                          >
                            <Select
                              onChange={val => onConditionTypeChange(val, group, item)}
                              placeholder={getMessage('Permission.perm_please_sele')}
                            >
                              {groupTypeData?.map(opt => (
                                <Option key={opt.value} value={opt.value} title={getMessage(opt.label)}>
                                  <TextWidget>{opt.label}</TextWidget>
                                </Option>
                              ))}
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col span={4}>
                          {item.Type == enumGroupType.Variable && (
                            <Form.Item
                              // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Variable.Key`}
                              name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Variable', 'Key']}
                              initialValue={item.Variable.Key || 'currentUser'}
                              rules={[{ required: true, message: getMessage('Permission.not_null') }]}
                            >
                              <Select
                                onChange={val => onUserTypeChange(val, group, item)}
                                placeholder={getMessage('Permission.perm_please_sele')}
                              >
                                {userTypeData?.map(opt => (
                                  <Option key={opt.value} value={opt.value} title={getMessage(opt.label)}>
                                    <TextWidget>{opt.label}</TextWidget>
                                  </Option>
                                ))}
                              </Select>
                            </Form.Item>
                          )}
                          {/* 值 */}
                          <Form.Item
                            style={{
                              display: item.Type == enumGroupType.Variable ? 'none' : 'block',
                            }}
                            // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Value`}
                            name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Value']}
                            initialValue={item.Value}
                            rules={
                              item.Type == enumGroupType.Input
                                ? ['isnull', 'isnotnull'].includes(item.Operator)
                                  ? [
                                    { max: 200, message: getMessage('Permission.max_leng_200') },
                                  ]
                                  : [
                                    { required: true, message: getMessage('Permission.not_null') },
                                    { max: 200, message: getMessage('Permission.max_leng_200') },
                                  ]
                                : ['user', 'department'].includes(item.Variable?.Key) ?
                                  [
                                    { required: true, message: getMessage('Permission.not_null') },
                                  ]
                                  : []}
                          >
                            <Input placeholder={getMessage('Permission.please_insert')} />
                          </Form.Item>
                        </Col>
                        {item.Type == enumGroupType.Variable &&
                          (item.Variable.Key == 'user' || item.Variable.Key == 'department') && (
                            <Col span={6}>
                              <Form.Item
                                // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].Name`}
                                name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'Name']}
                                initialValue={item.Name}
                                rules={[{ required: true, message: getMessage('Permission.not_null') }]}
                              >
                                <SelectUser
                                  data={item}
                                  onClick={() => openMemberSelect(group, 'condition', item)}
                                  onDelete={(tagIndex: number) => onDeleteTag(group, item, tagIndex)}
                                />
                              </Form.Item>

                              {/* 隐藏数据 */}
                              {item.MemberSelected?.map((member: any) => (
                                <div key={member.Id} style={{ display: 'none' }}>
                                  <Form.Item
                                    // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].MemberSelected[${member.Id}].key`}
                                    name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'MemberSelected', member.Id, 'key']}
                                    initialValue={member.key}
                                  >
                                    <Input hidden />
                                  </Form.Item>
                                  <Form.Item
                                    // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].MemberSelected[${member.Id}].Id`}
                                    name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'MemberSelected', member.Id, 'Id']}
                                    initialValue={member.Id}
                                  >
                                    <Input hidden />
                                  </Form.Item>
                                  <Form.Item
                                    // name={`DataPermGroup[${group.Id}].Conditions[${item.Id}].MemberSelected[${member.Id}].Name`}
                                    name={['DataPermGroup', group.Id, 'Conditions', item.Id, 'MemberSelected', member.Id, 'Name']}
                                    initialValue={member.Name}
                                  >
                                    <Input hidden />
                                  </Form.Item>
                                </div>
                              ))}
                              {/* 隐藏数据 */}
                            </Col>
                          )}
                        {/* 行内操作-添加/删除按钮 */}
                        <Col offset={item.Type == enumGroupType.Input || item.Variable.Key == 'currentUser' || item.Variable.Key == 'currentDepartment' ? 6 : 0} span={2} className='condition-btn'>
                          <InbizIcon
                            title={getMessage('Permission.addTo')} // 添加
                            onClick={() => onAddCondition(group, itemIndex)}
                            type="icon-ic-xinzeng"
                          />

                          {group.Conditions?.length > 1 && (
                            <InbizIcon
                              title={getMessage('Permission.delete')} // 删除
                              style={{ color: '#666', fontSize: 18 }}
                              onClick={() => onDeleteCondition(group, item)}
                              type="icon-daohang-huishouzhan"
                            />
                          )}
                        </Col>
                      </Row>
                    ))}

                    <Row style={{ padding: '0 10px' }}>
                      <Col>
                        <span
                          className='user-add-btn'
                          onClick={() => openMemberSelect(group, 'user')}
                        >
                          <InbizIcon type="icon-ic-xinzeng" /> <TextWidget>Permission.perm_add_object</TextWidget>{/* 添加权限对象 */}
                        </span>
                      </Col>
                    </Row>

                    <div className='user-perm'>
                      {group.MemberPermList?.map((item: any) => (
                        <Row key={item.MemberId}>
                          <Col span={6}>
                            <InbizIcon
                              type={
                                item.MemberType == 5
                                  ? 'icon-department'
                                  : item.MemberType == 3
                                    ? 'icon-group'
                                    : 'icon-user1'
                              }
                            />{' '}
                            {item.MemberName}
                          </Col>
                          <Col span={16}>
                            {/* 隐藏数据 */}
                            <Form.Item
                              style={{ display: 'none' }}
                              // name={`DataPermGroup[${group.Id}].MemberPermList[${item.MemberId}].MemberType`}
                              name={['DataPermGroup', group.Id, 'MemberPermList', item.MemberId, 'MemberType']}
                              initialValue={item.MemberType}
                            >
                              <Input hidden />
                            </Form.Item>
                            <Form.Item
                              style={{ display: 'none' }}
                              // name={`DataPermGroup[${group.Id}].MemberPermList[${item.MemberId}].MemberId`}
                              name={['DataPermGroup', group.Id, 'MemberPermList', item.MemberId, 'MemberId']}
                              initialValue={item.MemberId}
                            >
                              <Input hidden />
                            </Form.Item>
                            <Form.Item
                              style={{ display: 'none' }}
                              // name={`DataPermGroup[${group.Id}].MemberPermList[${item.MemberId}].MemberName`}
                              name={['DataPermGroup', group.Id, 'MemberPermList', item.MemberId, 'MemberName']}
                              initialValue={item.MemberName}
                            >
                              <Input hidden />
                            </Form.Item>
                            {/* 隐藏数据 */}

                            <Form.Item
                              // name={`DataPermGroup[${group.Id}].MemberPermList[${item.MemberId}].PermValue`}
                              name={['DataPermGroup', group.Id, 'MemberPermList', item.MemberId, 'PermValue']}
                              initialValue={valueAsArrayFormat(item.PermValue as Number)}
                            >
                              <Checkbox.Group
                                onChange={values => onChangeUserPerm(values, item, group)}
                              >
                                <Checkbox
                                  disabled={
                                    valueAsArrayFormat(item.PermValue as Number).includes(enumPerm.edit) ||
                                    valueAsArrayFormat(item.PermValue as Number).includes(enumPerm.delete)
                                  }
                                  value={1}
                                >
                                  {/* 查看 */}
                                  <TextWidget>Permission.view</TextWidget>
                                </Checkbox>
                                <Checkbox value={2}>
                                  {/* 编辑 */}
                                  <TextWidget>Permission.edit</TextWidget>

                                </Checkbox>
                                <Checkbox value={4}>
                                  {/* 删除 */}
                                  <TextWidget>Permission.delete</TextWidget>
                                </Checkbox>
                              </Checkbox.Group>
                            </Form.Item>
                          </Col>
                          <Col span={2} className='condition-btn'>
                            {group.MemberPermList.length !== 1 && (
                              <InbizIcon
                                title={getMessage('Permission.delete')} // 删除
                                onClick={() => onDeleteUser(group, item)}
                                type="icon-daohang-huishouzhan"
                              />
                            )}
                          </Col>
                        </Row>
                      ))}
                    </div>
                  </div >
                </div >
              </>
            ))}
          </Form >
        ) : (
          <PageLoading />
        )}
      </Modal >
      {memberSelectVisible && <MemberSelect {...memberSelectProps} />}
    </>
  )
}
export default RoleConfig